package com.tree.userservice.controller;

import com.tree.userservice.dto.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * @ClassName com.tree.userservice.controller
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-07-06 19:16
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    private static final String INSTANCE_ID = "user-service";

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/index")
    public String index(){
        //get service instance from eureka
        ServiceInstance serviceInstance = discoveryClient.getInstances(INSTANCE_ID).get(0);

        log.info("==> /index, host={},service-id={}", serviceInstance.getHost(),serviceInstance.getServiceId());
        return "User-Service";
    }

    /**
     * 带参数
     * @param id
     * @param name
     * @param age
     * @return
     */
    @GetMapping("/hello/{name}/{age}")
    public User hello(@RequestHeader Integer id ,@PathVariable String name, @PathVariable Integer age){
        log.info("==> /hello, id={},name={},age-id={}", id,name,age);

        return new User(id, name,age);
    }

    /**
     * 带参数
     * @param user
     * @return
     */
    @PostMapping("/hello2")
    public String hello2(@RequestBody User user){
        log.info("==> /hello2, user={}", user);
        return user.toString();
    }

    @GetMapping("/time")
    public String time(){
        return "time";
    }

    @GetMapping("/longtime")
    public String longTime() throws InterruptedException {
        Thread.sleep(2*1000);
        return "sleep 3s time";
    }

    @GetMapping("/randomtime")
    public String randomTime() throws InterruptedException {
        ServiceInstance serviceInstance = discoveryClient.getInstances(INSTANCE_ID).get(0);
        //测试超时
        int sleepTime = new Random().nextInt(3000);
        Thread.sleep(sleepTime);
        log.info("==> /randomTime, now={},sleep={}s,host={},service-id={}", LocalDateTime.now(),sleepTime, serviceInstance.getHost(),serviceInstance.getServiceId());

        return "randomTime:"+sleepTime;
    }
}
